package com.hf.bill

import com.hf.constant.OrderLunchConst
import com.hf.date.DateUtils
import com.hf.mail.AbstractMailService
import com.hf.mail.MailMessage
import com.hf.order.OrderPeriod
import com.hf.order.OrderPeriodService
import com.hf.order.UserOrderHistory
import com.hf.order.UserOrderHistoryService
import com.hf.security.OrderUser
import com.hf.template.GspTemplateUtils

class MailBillLastWorkdayOfPeriodService extends AbstractMailService {

	UserOrderHistoryService userOrderHistoryService
	UserBillPeriodHistoryService userBillPeriodHistoryService
	OrderPeriodService orderPeriodService

	void sendMail() {
		List<Date> periodStartEndDay	= DateUtils.getPeriodStartEndDay()
		OrderPeriod orderPeriod = orderPeriodService.getCurrentOrderPeriod(periodStartEndDay)
		Map<OrderUser, List<UserOrderHistory>> userOrderHistoryMap = userOrderHistoryService.getUserOrderHistoryOfPeriodMap(periodStartEndDay)

		String subject = OrderLunchConst.FROM_ORDER_LUNCH + "This week bill info  " + DateUtils.getPeriodStartEndDayString()
		for(Map.Entry<OrderUser, List<UserOrderHistory>> userOrderHistoryEntry : userOrderHistoryMap.entrySet()) {
			OrderUser user = userOrderHistoryEntry.key
			if(OrderLunchConst.IS_TEST && user.name != OrderLunchConst.ADMIN_NAME) {
				continue;
			}
			List<UserOrderHistory> userOrderHistorySet =  userOrderHistoryEntry.value.sort { a, b ->
				a.orderDate <=> b.orderDate
			}
			UserBillPeriodHistory userBillPeriodHistory = userBillPeriodHistoryService.getUserBillPeriodHistory(orderPeriod, user, userOrderHistorySet.size())
			send(user, userOrderHistorySet, userBillPeriodHistory,  subject)

			if(!OrderLunchConst.IS_TEST && user.name != OrderLunchConst.ADMIN_NAME) {
				user.oweMoney = userBillPeriodHistory.getTotalMoney()
				user.isPaid = false
				user.save()
			}
		}
	}

	private void send(OrderUser user, List<UserOrderHistory> userOrderHistoryList, UserBillPeriodHistory userBillPeriodHistory, String subject) {
		MailMessage mail = new MailMessage()
		mail.to = [user.email]

		mail.subject = subject
		mail.htmlText = GspTemplateUtils.renderTemplate('/bill/emailUserPeriodBill', [userOrderHistoryList : userOrderHistoryList, userBillPeriodHistory : userBillPeriodHistory])

		mailSenderService.sendAsyn(mail)
	}
}
